#include <config.h>
#include <debug.h>
#include <header.h>
#include <rules.h>
#include <xml_util.h>

#include "gui.h"
#include "eggtrayicon.h"
#include "language.h"
static GtkWidget *load_image(const gchar * filename);
static gboolean tray_button_release_event(GtkWidget * button, GdkEventButton * event);
static void pop_tray_icon(GdkEventButton *event);
static GtkItemFactoryEntry menu_items[] = {
  { "/_Preference", NULL, show_main_window, 0, "<StockItem>", GTK_STOCK_PREFERENCES},
  { "/sep",          NULL,    NULL,          0, "<Separator>"},
  { "/_Quit",       NULL, gtk_main_quit,     0, "<StockItem>", GTK_STOCK_QUIT},
};

enum
{
  LEFT_BUTTON = 1,
  MIDDLE_BUTTON = 2,
  RIGHT_BUTTON = 3
};

void init_tray_icon(void)
{
  GtkWidget *image = NULL;
  GtkWidget *event_box = NULL;
  GtkTooltips *tooltips = NULL;
  EggTrayIcon *tray_icon = NULL;
  tray_icon = egg_tray_icon_new("Coolnet tray icon");
  event_box = gtk_event_box_new();
  gtk_container_add(GTK_CONTAINER(tray_icon), event_box);
  g_signal_connect(G_OBJECT(event_box), "button-release-event",
                   G_CALLBACK(tray_button_release_event), NULL);
  tooltips = gtk_tooltips_new();
  gtk_tooltips_set_tip(GTK_TOOLTIPS(tooltips), event_box,
                       TEXT_TRAYICON_TIPS, NULL);
  image = load_image(COOLNET_TRAY_ICON);
  gtk_container_add(GTK_CONTAINER(event_box), image);
  gtk_widget_show_all(GTK_WIDGET(tray_icon));
}

static GtkWidget *load_image(const gchar * filename)
{
  GtkWidget *image = NULL;
  GdkPixbuf *pixbuf = NULL;
  pixbuf = gdk_pixbuf_new_from_file(filename, NULL);
  if (!pixbuf)
  {
    image = gtk_image_new_from_stock(GTK_STOCK_HOME,
                                     GTK_ICON_SIZE_MENU);
  }
  else
  {
    image = gtk_image_new_from_pixbuf(pixbuf);
  }
  return image;
}

static gboolean tray_button_release_event (GtkWidget * button, GdkEventButton * event)
{
  /* ignore double-click or any others */
  g_return_val_if_fail ((event->type == GDK_BUTTON_RELEASE), FALSE);
  switch (event->button)
  {
    case LEFT_BUTTON:
      /* show main window */
      __GUI_DEBUG("Press left button\n");
      show_main_window();
      break;
    case MIDDLE_BUTTON:
      __GUI_DEBUG("Press middle button\n");
      break;
    case RIGHT_BUTTON:
      __GUI_DEBUG("Press right button\n");
      pop_tray_icon(event);
      break;
    default:
      return FALSE;
  }
  return TRUE;
}

static void pop_tray_icon(GdkEventButton *event)
{
  GtkItemFactory *item_factory = NULL;
  GtkWidget *pop_menu = NULL;
  gint nmenu_items = sizeof (menu_items) / sizeof (menu_items[0]);
  item_factory = gtk_item_factory_new(GTK_TYPE_MENU, "<main>", NULL);
  gtk_item_factory_create_items(item_factory, nmenu_items, menu_items, NULL);
  pop_menu = gtk_item_factory_get_widget(item_factory, "<main>");
  gtk_menu_popup(GTK_MENU(pop_menu), NULL, NULL, NULL, NULL,
                 event->button, event->time);
}

